package com.victualler.core.common.filter;




import com.victualler.core.common.dto.ResultDto;
import com.victualler.core.common.io.InterfaceOutputStream;
import com.victualler.core.common.utils.JsonUtil;
import com.victualler.core.common.wapper.CustomRequestWapper;
import com.victualler.core.common.wapper.CustomResponseWapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Aouthor Guoshichang
 * @Date 13:52 on 2018/4/8.
 * @Function 统一拦截接口响应相关的过滤器
 */
@WebFilter(filterName = "restWapperFilter", urlPatterns = {"/*"})
public class RestWapperFilter implements Filter {
	/**
	 * 日志记录
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(RestWapperFilter.class); 
	/*
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
	@Override
	public void init(FilterConfig config) throws ServletException {
		// filter不能通过注解获取spring的Bean实例,此处使用servlet上下文凡是获得配置信息的bean实例
		// weblogic通过上下文获取有问题，暂时改为直接读取文件的形式


	}

	/*
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//暂时取消
		if(this.canIgnore((HttpServletRequest)request)){
			chain.doFilter(request, response);
			return ;
		}else{
			CustomRequestWapper requestWrapper = new CustomRequestWapper((HttpServletRequest) request);
			CustomResponseWapper responseWrapper = new CustomResponseWapper((HttpServletResponse) response);
			//取请求内容
			ResultDto resultDto = null;
			try{
				chain.doFilter(requestWrapper, responseWrapper);
				//获取请求相应的内容
				Object result = this.getResponseResult(responseWrapper);
				resultDto = new ResultDto(result);
			}catch(Exception e){
				//封装返回值
				e.printStackTrace();
				resultDto = new ResultDto(e.getMessage());
			}

			//包装结果对象
			String resultWapper= JsonUtil.toJsonString(resultDto, true);
			System.out.println(resultWapper);
			//输出到response中
			this.resetResponse(responseWrapper,resultWapper);
			responseWrapper.finishResponse();
		} 
	}
	
	/**
	 * @author Guoshichang   
	 * @date 21:23 on 2018/6/26.
	 * @param responseWrapper
	 * @function 从流中重新获取对象
	 */
	public Object getResponseResult(CustomResponseWapper responseWrapper){
		String preContent = this.getContent(responseWrapper);
		Object result = null;
		try{
			  //可转换为json对象
			result = JsonUtil.toJavaObject(preContent, Object.class);
		}catch(Exception e) {
			 //原始内容
			 result = preContent;
		} 
		return result;
	}
	
	/**
	 * 重置内容部分
	 * @param responseWrapper
	 * @param content
	 * @throws IOException
	 */
	public void resetResponse(CustomResponseWapper responseWrapper, String content) throws IOException{
		responseWrapper.reset();
		InterfaceOutputStream outPutStream = (InterfaceOutputStream) responseWrapper.getOutputStream();
		outPutStream.getByteArrayOutputStream().reset();
		//字符流的形式进行输出
		outPutStream.getByteArrayOutputStream().write(content.getBytes("UTF-8"));
	}
	
	public String getContent(CustomResponseWapper responseWrapper){
		InterfaceOutputStream outPutStream;
		try {
			outPutStream = (InterfaceOutputStream) responseWrapper.getOutputStream();
			return outPutStream.getResult("UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return null;
		}
	}
	
	
	/**
	 * @Aouthor Guoshichang
	 * @Date 11:37 on 2018/6/13.
	 * @param request
	 * @Function  过滤静态资源
	 */
	private boolean canIgnore(HttpServletRequest request){
		if(request.getServletPath().startsWith("/favicon.ico") ||
		   	request.getServletPath().startsWith("/css") ||
		   	request.getServletPath().startsWith("/img") ||
		   	request.getServletPath().startsWith("/js") ||
			request.getServletPath().startsWith("/show") ||
			request.getServletPath().startsWith("/config/img/loadImg") ||
		   	request.getServletPath().startsWith("/login") ||
			request.getServletPath().indexOf("/exportFile") != -1  //导出文件
				){
			return true;
		}
		return false;
	}
	
	/*
     * @see javax.servlet.Filter#destroy()
     */
	@Override
	public void destroy() {
	}


}
